package com.example.studentaihouduan.service.Serviceimpl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.studentaihouduan.Mapper.UserMapper;
import com.example.studentaihouduan.entity.Role;
import com.example.studentaihouduan.entity.User;
import com.example.studentaihouduan.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User findByUsername(String username) {
        User user = lambdaQuery().eq(User::getUsername, username).one();
        if (user != null) {
            List<Role> roles = userMapper.findRolesByUserId(user.getId());
            user.setRoles(roles);
        }
        return user;
    }

    @Override
    public boolean save(User user) {
        // 校验用户名是否已存在
        User existingUser = lambdaQuery().eq(User::getUsername, user.getUsername()).one();
        if (existingUser != null) {
            throw new RuntimeException("用户名已存在");
        }

        // 插入用户到数据库
        return userMapper.insert(user) > 0;
    }

}